import React, { useEffect, useState } from "react";
import "./Login.css";
import Index from "../../components/bg";
import { Dialog } from "react-vant";
import { useNavigate } from "react-router";
import RBACManager from "../../utils/rbacManager";
import { ROLES } from "../../config/permissions";

const Login = () => {
  const [formData, setFormData] = useState({
    email: "",
    password: "",
    rememberMe: false,
  });
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState("");

  const navigate = useNavigate();

  // 获取所有可登录的邮箱（包括注册用户和团队成员）
  const getAllowedEmails = () => {
    try {
      const registeredUser = localStorage.getItem("registerStep1");
      const teamData = localStorage.getItem("teamData");
      let allowedEmails = [];

      // 添加注册用户的邮箱
      if (registeredUser) {
        const userData = JSON.parse(registeredUser);
        if (userData.email) {
          allowedEmails.push({
            email: userData.email,
            password: userData.password,
            isAdmin: true,
          });
        }
      }

      // 添加团队成员的邮箱
      if (teamData) {
        const parsedTeamData = JSON.parse(teamData);
        if (parsedTeamData.members && Array.isArray(parsedTeamData.members)) {
          parsedTeamData.members.forEach((member) => {
            // 确保不重复添加邮箱
            if (!allowedEmails.some((user) => user.email === member.email)) {
              allowedEmails.push({
                email: member.email,
                password: "123456", // 团队成员默认密码
                isAdmin: false,
              });
            }
          });
        }
      }

      console.log("Allowed emails:", allowedEmails); // 调试用
      return allowedEmails;
    } catch (error) {
      console.error("Error parsing stored data:", error);
      return [];
    }
  };

  const handleInputChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: type === "checkbox" ? checked : value,
    }));
    setError("");
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    try {
      const allowedUsers = getAllowedEmails();
      const user = allowedUsers.find((user) => user.email === formData.email);

      // 验证表单
      if (!formData.email.trim()) {
        setError("请输入邮箱地址");
        return;
      }

      if (!formData.password.trim()) {
        setError("请输入密码");
        return;
      }

      // 验证密码
      if (user.password !== formData.password) {
        if (user.isAdmin) {
          setError("密码错误，请重新输入");
        } else {
          setError("团队成员首次登录密码为：123456");
        }
        return;
      }

      // 存储登录状态和用户信息
      localStorage.setItem("isLoggedIn", "true");
      localStorage.setItem(
        "currentUser",
        JSON.stringify({
          email: formData.email,
          isAdmin: user.isAdmin,
          loginTime: new Date().toISOString(),
        })
      );

      if (user && user.password === formData.password) {
        // 设置用户权限
        const userData = {
          email: user.email,
          role: user.isAdmin ? ROLES.ADMIN : ROLES.MEMBER,
          position: localStorage.getItem("registerStep2")
            ? JSON.parse(localStorage.getItem("registerStep2")).position
            : "普通员工",
        };

        // 设置权限和认证状态
        RBACManager.setUserPermissions(userData);

        // 保存登录状态
        localStorage.setItem("isLoggedIn", "true");

        if (formData.rememberMe) {
          localStorage.setItem("rememberedEmail", formData.email);
        }

        // 根据角色跳转到相应的仪表盘
        setTimeout(() => {
          navigate(user.isAdmin ? "/admin-dashboard" : "/member-dashboard");
        }, 1000);
      } else {
        setError(user ? "密码错误" : "该邮箱未注册或不在团队成员中");
      }
    } catch (error) {
      console.error("Login error:", error);
      setError("登录过程中出现错误，请重试");
    }
  };

  // 检查记住的邮箱和登录状态
  useEffect(() => {
    const rememberedEmail = localStorage.getItem("rememberedEmail");
    if (rememberedEmail) {
      setFormData((prev) => ({
        ...prev,
        email: rememberedEmail,
        rememberMe: true,
      }));
    }

    // 如果已经登录，根据用户类型跳转
    const currentUser = localStorage.getItem("currentUser");
    if (currentUser) {
      const user = JSON.parse(currentUser);
      navigate(user.isAdmin ? "/admin-dashboard" : "/member-dashboard");
    }
  }, [navigate]);

  return (
    <div className="login">
      <Index />
      <div className="login-container">
        <h3>欢迎登录有料素材</h3>
        <form onSubmit={handleSubmit}>
          {error && <div className="error-messages">{error}</div>}
          <div className="form-group">
            <label>Email</label>
            <input
              type="email"
              name="email"
              value={formData.email}
              onChange={handleInputChange}
              placeholder="youliao@gmail.com"
              className={error && error.includes("邮箱") ? "error" : ""}
            />
          </div>

          <div className="form-group">
            <label>密码</label>
            <div className="password-input">
              <input
                type={showPassword ? "text" : "password"}
                name="password"
                value={formData.password}
                onChange={handleInputChange}
                placeholder="········"
                className={error && error.includes("密码") ? "error" : ""}
              />
              <span
                className="password-toggle"
                onClick={() => setShowPassword(!showPassword)}
              >
                {showPassword ? "👁️" : "👁️"}
              </span>
            </div>
          </div>

          <div className="form-options">
            <label className="checkbox-label">
              <input
                type="checkbox"
                name="rememberMe"
                checked={formData.rememberMe}
                onChange={handleInputChange}
              />
              <p>记住我</p>
            </label>
            <a href="/forgot-password">忘记密码?</a>
          </div>

          <button type="submit" className="login-button">
            立即登录
          </button>

          <div className="register-link">
            还没有账号？ <a href="/step1">去注册</a>
          </div>
        </form>
      </div>
    </div>
  );
};

export default Login;
